using IcsSEMCtrl.Global.Device;
using IcsSEMCtrl.Global.Exception;
using IcsSEMCtrl.Service.Logger;
using IcsSEMCtrl.Service.Material;
using IcsSEMCtrl.Util.Client;
using Lifter.Device.Unit;
using Lifter.Event.Lifter;
using Lifter.Global;
using Lifter.Global.Device;
using Lifter.Utility;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Permissions;
using System.Threading;
using System.Timers;
using TKT.Lifter.CIM.Lifter.Device.Service;
using TKT.Lifter.CIM.Lifter.Device.Unit;
using TKT.Lifter.CIM.Lifter.Global;
using TKT.Lifter.CIM.Lifter.Gui.Monitor.Panels;
using static TKT.Lifter.CIM.Lifter.Device.Unit.LifterTower;
using static TKT.Lifter.CIM.Lifter.Device.Unit.ShuttleMaster;

namespace Lifter.Device.Dispatcher
{
    [HostProtection(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
    public class LifterDispatcher
    {
        public const string CLASS = "LifterDispatcher";
        public List<TransferWorkItem> workList = new List<TransferWorkItem>();
        public object workList_monitor = new object();
        protected bool running = false;
        protected Thread theThread = null;
        protected LifterSEM hostDevice = null;
        protected bool keepWorking = false;
        protected WorkItemComparer workItemComparer = null;
        protected static object wait_monitor = new object();
        private ShuttleMaster shuttleMaster = null;
        public System.Timers.Timer refreshCommandTimer = new System.Timers.Timer(); //刷新指令集合，判断指令集合是否为空
        private System.Timers.Timer commandTimeOutTimer = new System.Timers.Timer();
        private bool shortcutCreateCommandFlag;//快捷方式创建指令标识
        public string ShortcutCreateCommandSource; //快捷方式创建指令起始地
        public string ShortcutCreateCommandDest; //快捷方式创建指令目的地

        public bool ShortcutCreateCommandFlag { get => shortcutCreateCommandFlag; set => shortcutCreateCommandFlag = value; }

        public LifterDispatcher()
        {
        }
        public LifterDispatcher(LifterSEM owner)
        {
            this.hostDevice = owner;
            this.workList = TransferWorkItem.LoadWorkItems();
            this.workItemComparer = new WorkItemComparer();
            this.shuttleMaster = this.hostDevice.ShuttleMaster;
            this.shuttleMaster.lftSem = owner;
            this.running = false;

            refreshCommandTimer.Elapsed += new ElapsedEventHandler(refreshCommand);
            refreshCommandTimer.Interval = 200;
            refreshCommandTimer.Start();
        }
        protected bool IsRunning()
        {
            return this.running;
        }
        public void Start()
        {

            //初始化transfer是否执行的timer
            commandTimeOutTimer.Elapsed += new ElapsedEventHandler(this.Run);
            commandTimeOutTimer.Interval = 1000;
            commandTimeOutTimer.Start();
            /*            bool flag = false;
                        try
                        {
                            Monitor.Enter(this, ref flag);
                            if (!this.running)
                            {
                                this.running = true;
                                this.theThread = new Thread(new ThreadStart(this.Run));
                                this.theThread.Name = "LifterDispatcher-" + this.hostDevice.ToString();
                                this.theThread.IsBackground = true;
                                this.theThread.Start();
                            }
                        }
                        finally
                        {
                            if (flag)
                            {
                                Monitor.Exit(this);
                            }
                        }*/
        }
        public void Stop()
        {
            lock (LifterDispatcher.wait_monitor)
            {
                this.running = false;
                Monitor.PulseAll(LifterDispatcher.wait_monitor);
            }
        }
        public void Wakeup()
        {
            lock (LifterDispatcher.wait_monitor)
            {
                this.keepWorking = true;
                Monitor.PulseAll(LifterDispatcher.wait_monitor);
            }
        }
        /// <summary>
        /// 工作线程，当有port状态为WaitIn时，创建命令，执行命令。
        /// 循环执行上述流程。
        /// </summary>
        public void Run(object sender, ElapsedEventArgs e)
        {
            if (this.hostDevice.DeviceState != enumRIDState.DOWN)
            {
                commandTimeOutTimer.Stop();
                //1.检查Port有CST WaitIn状态;
                //2.MES未发Command，导致超时;
                //3.CIMPC本地创建命令.
                this.hostDevice.CreateCarrierCommandByTimeOut();
                this.CheckingTransferWork();
                commandTimeOutTimer.Start();
            }

            /*//判断系统是否为run状态
            while (this.IsRunning())
            {
                try
                {
                    do
                    {
                        lock (this.workList_monitor)
                        {
                            if (this.workItemComparer != null)
                            {
                                //根据优先级进行排序。
                                this.workList.Sort(this.workItemComparer);
                            }
                        }
                        //1.检查Port有CST WaitIn状态;
                        //2.MES未发Command，导致超时;
                        //3.CIMPC本地创建命令.
                        this.hostDevice.CreateCarrierCommandByTimeOut();
                        this.CheckingTransferWork();
                    }
                    while (this.keepWorking);
                }
                catch (Exception ex)
                {
                    Log.log(3, "LifterDispatcherrun", "debug", Category.DEBUG, "", "dispatcher", " dispatcher error");
                    Log.log(3, "LifterDispatcherrun", "debug", Category.DEBUG, "", "dispatcher", ex.Message.ToString());
                }
                //this.WaitForWork();
            }*/
        }
        #region 新Lifter系统搬送指令逻辑 add by yangshl
        /// <summary>
        /// add by yangshl 2023/9/27
        /// Timer刷新指令集合，判断指令集合是否有值
        /// </summary>
        private void refreshCommand(object sender, ElapsedEventArgs e)
        {
            this.refreshCommandTimer.Stop();
            //判断指令集合是否有值
            if (this.workList != null && this.workList.Count > 0)
            {
                this.DoFirstMoveCommand();
            }
            else
            {
                this.refreshCommandTimer.Start();
            }
        }
        /// <summary>
        /// add by yangshl 2023/9/12
        /// 创建轿厢移动指令
        /// </summary>
        public CimToPLCCommandInfo CreateShuttleMoveCommand()
        {
            CimToPLCCommandInfo cimToPLCCommandInfo = new CimToPLCCommandInfo();
            //判断轿厢是否在1楼，或者轿厢内是否为空
            if (shuttleMaster.ShuttleFloor == 10 || shuttleMaster.ShuttleIsEmpty())
            {
                //获取Move指令目的地楼层
                cimToPLCCommandInfo = this.Floor1FOrShuttleIsEmpty();
            }
            else//轿厢不在1F，且轿厢内有物料
            {
                cimToPLCCommandInfo = this.ShuttleNotEmptyAndNotIn1F();
            }
            this.shuttleMaster.ShuttleLocationCommand = cimToPLCCommandInfo;
            return cimToPLCCommandInfo;
        }
        /// <summary>
        /// add by yangshl 2023/9/14
        /// //轿厢不在1F，且轿厢内有物料
        /// </summary>
        /// <returns>返回Move指令楼层</returns>
        private CimToPLCCommandInfo ShuttleNotEmptyAndNotIn1F()
        {
            CimToPLCCommandInfo floor = new CimToPLCCommandInfo();
            //根据轿厢的工作模式，处理不同的逻辑
            switch (shuttleMaster.ShuttleWorkModeType)
            {
                case ShuttleWorkMode.SHUTTLE_RECEIVE://轿厢是接料工作模式
                    floor = this.GetMoveCommandByShuttleMode(this.JudgeShuttleIsFull());
                    break;
                case ShuttleWorkMode.SHUTTLE_SEND://轿厢是送料工作模式
                    floor = this.GetMoveCommandByShuttleMode(true);
                    break;
                case ShuttleWorkMode.SHUTTLE_SENDANDRECEIVE://轿厢是接收同步工作模式
                    floor = this.GetMoveCommandByShuttleMode(this.JudgeShuttleIsFull());
                    break;
                default:
                    break;
            }
            return floor;
        }
        /// <summary>
        /// add by yangshl 2023/9/14
        /// 判断接料轿厢是否都为满状态
        /// </summary>
        /// <returns></returns>
        private bool JudgeShuttleIsFull()
        {
            bool isFull = true;
            bool ResultFull = true;
            if (this.shuttleMaster.IsOnlyUseBehindVehicle)
            {
                //判断所有UnLoader指令所在的CV对应的轿厢是否已满
                List<TransferWorkItem> transferWorks = this.hostDevice.LDispatcher.GetTransferCommandByStatus(enumTransferState.LOADREQ);
                foreach (TransferWorkItem transferWorkItem in transferWorks)
                {
                    isFull = true;
                    LifterPort lifterPort = this.hostDevice.GetLifterPort(transferWorkItem.Source.Trim());
                    if (lifterPort != null)
                    {
                        if (lifterPort.Floor <= this.shuttleMaster.ShuttleFloor)
                        {
                            foreach (ConveyorBuffer conveyor in this.hostDevice.ConveyorBuffers.Values)
                            {
                                if (ConveyorBuffer.Constants.CVUNLOAD.Equals(conveyor.Cvtype) && conveyor.LifterPortID.Equals(lifterPort.ElementId))
                                {
                                    List<string> shuttles = conveyor.Shuttles;
                                    foreach (string shuttleID in shuttles)
                                    {
                                        Vehicle vehicle = this.hostDevice.GetVehicle(shuttleID);
                                        if (vehicle != null && Vehicle.Constants.BEHIND.Equals(vehicle.ShuttleAroundPosition) && string.IsNullOrWhiteSpace(vehicle.CommandId))
                                        {
                                            isFull = false;
                                        }
                                    }
                                    if (isFull)
                                    {
                                        //当前指令所在出料CV绑定的轿厢已满，无法入料
                                        transferWorkItem.enableTransferIn = false;
                                    }
                                    else
                                    {
                                        transferWorkItem.enableTransferIn = true;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        ConveyorBuffer conveyorBuffer = this.hostDevice.GetConveyorBuffer(transferWorkItem.Source.Trim());
                        if (conveyorBuffer != null && conveyorBuffer.Floor <= this.shuttleMaster.ShuttleFloor)
                        {
                            List<string> shuttles = conveyorBuffer.Shuttles;
                            foreach (string shuttleID in shuttles)
                            {
                                Vehicle vehicle = this.hostDevice.GetVehicle(shuttleID);
                                if (vehicle != null && Vehicle.Constants.BEHIND.Equals(vehicle.ShuttleAroundPosition) && string.IsNullOrWhiteSpace(vehicle.CommandId))
                                {
                                    isFull = false;
                                }
                            }
                            if (isFull)
                            {
                                //当前指令所在出料CV绑定的轿厢已满，无法入料
                                transferWorkItem.enableTransferIn = false;
                            }
                            else
                            {
                                transferWorkItem.enableTransferIn = true;
                            }
                        }
                    }
                }
                foreach(TransferWorkItem transferWorkItem in transferWorks)
                {
                    if (transferWorkItem.enableTransferIn)
                    {
                        ResultFull = false;
                    }
                }
            }
            else
            {
                //判断所有UnLoader指令所在的CV对应的轿厢是否已满
                List<TransferWorkItem> transferWorks = this.hostDevice.LDispatcher.GetTransferCommandByStatus(enumTransferState.LOADREQ);
                foreach (TransferWorkItem transferWorkItem in transferWorks)
                {
                    isFull = true;
                    LifterPort lifterPort = this.hostDevice.GetLifterPort(transferWorkItem.Source.Trim());
                    if (lifterPort != null)
                    {
                        if (lifterPort.Floor <= this.shuttleMaster.ShuttleFloor)
                        {
                            foreach (ConveyorBuffer conveyor in this.hostDevice.ConveyorBuffers.Values)
                            {
                                if (ConveyorBuffer.Constants.CVUNLOAD.Equals(conveyor.Cvtype) && conveyor.LifterPortID.Equals(lifterPort.ElementId))
                                {
                                    List<string> shuttles = conveyor.Shuttles;
                                    foreach (string shuttleID in shuttles)
                                    {
                                        Vehicle vehicle = this.hostDevice.GetVehicle(shuttleID);
                                        if (vehicle != null && string.IsNullOrWhiteSpace(vehicle.CommandId))
                                        {
                                            isFull = false;
                                        }
                                    }
                                    if (isFull)
                                    {
                                        //当前指令所在出料CV绑定的轿厢已满，无法入料
                                        transferWorkItem.enableTransferIn = false;
                                    }
                                    else
                                    {
                                        transferWorkItem.enableTransferIn = true;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        ConveyorBuffer conveyorBuffer = this.hostDevice.GetConveyorBuffer(transferWorkItem.Source.Trim());
                        if (conveyorBuffer != null && conveyorBuffer.Floor <= this.shuttleMaster.ShuttleFloor)
                        {
                            List<string> shuttles = conveyorBuffer.Shuttles;
                            foreach (string shuttleID in shuttles)
                            {
                                Vehicle vehicle = this.hostDevice.GetVehicle(shuttleID);
                                if (vehicle != null && string.IsNullOrWhiteSpace(vehicle.CommandId))
                                {
                                    isFull = false;
                                }
                            }
                            if (isFull)
                            {
                                //当前指令所在出料CV绑定的轿厢已满，无法入料
                                transferWorkItem.enableTransferIn = false;
                            }
                            else
                            {
                                transferWorkItem.enableTransferIn = true;
                            }
                        }
                    }
                }
                foreach (TransferWorkItem transferWorkItem in transferWorks)
                {
                    if (transferWorkItem.enableTransferIn)
                    {
                        ResultFull = false;
                    }
                }
            }
            return ResultFull;
        }
        /// <summary>
        /// add by yangshl 2023/9/14
        /// 判断轿厢出料是否都为满状态
        /// </summary>
        /// <returns></returns>
        private bool JudgeShuttleOutIsFull()
        {
            bool portIsFull = true;
            //判断所有UnLoader指令所在的CV对应的轿厢是否已满
            List<TransferWorkItem> transferWorksOnShuttle = this.hostDevice.LDispatcher.GetTransferCommandOnShuttle();
            foreach (TransferWorkItem transferWorkItem in transferWorksOnShuttle)
            {
                LifterPort lifterPort = this.hostDevice.GetLifterPort(transferWorkItem.Dest.Trim());
                if (lifterPort != null)
                {
                    foreach (ConveyorBuffer conveyorBuffer in this.shuttleMaster.lftSem.ConveyorBuffers.Values)
                    {
                        if (conveyorBuffer.LifterPortID.Equals(lifterPort.ElementId) && ConveyorBuffer.Constants.CVLOAD.Equals(conveyorBuffer.Cvtype) && (!string.IsNullOrWhiteSpace(conveyorBuffer.CSTID) || conveyorBuffer.CstPresence))
                        {
                            transferWorkItem.enableTransferOut = false;
                            break;
                        }
                        else
                        {
                            transferWorkItem.enableTransferOut = true;
                        }
                    }
                }
                else
                {
                    LogHelper.loggerInfo("在JudgeShuttleOutIsFull方法中，指令的目的地为空");
                }
            }
            foreach (TransferWorkItem transferWorkItem in transferWorksOnShuttle)
            {
                if (transferWorkItem.enableTransferOut)
                {
                    portIsFull = false;
                    break;
                }
            }
            return portIsFull;
        }
        private bool JudgeShuttleIsFull1F()
        {
            bool isFull = true;
            bool ResultFull = true;
            if (this.shuttleMaster.IsOnlyUseBehindVehicle)
            {
                //判断所有UnLoader指令所在的CV对应的轿厢是否已满
                List<TransferWorkItem> transferWorks = this.hostDevice.LDispatcher.GetTransferCommandByStatus(enumTransferState.LOADREQ);
                foreach (TransferWorkItem transferWorkItem in transferWorks)
                {
                    isFull = true;
                    LifterPort lifterPort = this.hostDevice.GetLifterPort(transferWorkItem.Source.Trim());
                    if (lifterPort != null)
                    {
                        if (lifterPort.Floor > this.shuttleMaster.ShuttleFloor)
                        {
                            foreach (ConveyorBuffer conveyor in this.hostDevice.ConveyorBuffers.Values)
                            {
                                if (ConveyorBuffer.Constants.CVUNLOAD.Equals(conveyor.Cvtype) && conveyor.LifterPortID.Equals(lifterPort.ElementId))
                                {
                                    List<string> shuttles = conveyor.Shuttles;
                                    foreach (string shuttleID in shuttles)
                                    {
                                        Vehicle vehicle = this.hostDevice.GetVehicle(shuttleID);
                                        if (vehicle != null && Vehicle.Constants.BEHIND.Equals(vehicle.ShuttleAroundPosition) && string.IsNullOrWhiteSpace(vehicle.CommandId))
                                        {
                                            isFull = false;
                                        }
                                    }
                                    if (isFull)
                                    {
                                        //当前指令所在出料CV绑定的轿厢已满，无法入料
                                        transferWorkItem.enableTransferIn = false;
                                    }
                                    else
                                    {
                                        transferWorkItem.enableTransferIn = true;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        ConveyorBuffer conveyorBuffer = this.hostDevice.GetConveyorBuffer(transferWorkItem.Source.Trim());
                        if (conveyorBuffer != null && conveyorBuffer.Floor > this.shuttleMaster.ShuttleFloor)
                        {
                            List<string> shuttles = conveyorBuffer.Shuttles;
                            foreach (string shuttleID in shuttles)
                            {
                                Vehicle vehicle = this.hostDevice.GetVehicle(shuttleID);
                                if (vehicle != null && Vehicle.Constants.BEHIND.Equals(vehicle.ShuttleAroundPosition) && string.IsNullOrWhiteSpace(vehicle.CommandId))
                                {
                                    isFull = false;
                                }
                            }
                            if (isFull)
                            {
                                //当前指令所在出料CV绑定的轿厢已满，无法入料
                                transferWorkItem.enableTransferIn = false;
                            }
                            else
                            {
                                transferWorkItem.enableTransferIn = true;
                            }
                        }
                    }
                }
                foreach (TransferWorkItem transferWorkItem in transferWorks)
                {
                    if (transferWorkItem.enableTransferIn)
                    {
                        ResultFull = false;
                    }
                }
            }
            else
            {
                //判断所有UnLoader指令所在的CV对应的轿厢是否已满
                List<TransferWorkItem> transferWorks = this.hostDevice.LDispatcher.GetTransferCommandByStatus(enumTransferState.LOADREQ);
                foreach (TransferWorkItem transferWorkItem in transferWorks)
                {
                    isFull = true;
                    LifterPort lifterPort = this.hostDevice.GetLifterPort(transferWorkItem.Source.Trim());
                    if (lifterPort != null)
                    {
                        if (lifterPort.Floor > this.shuttleMaster.ShuttleFloor)
                        {
                            foreach (ConveyorBuffer conveyor in this.hostDevice.ConveyorBuffers.Values)
                            {
                                if (ConveyorBuffer.Constants.CVUNLOAD.Equals(conveyor.Cvtype) && conveyor.LifterPortID.Equals(lifterPort.ElementId))
                                {
                                    List<string> shuttles = conveyor.Shuttles;
                                    foreach (string shuttleID in shuttles)
                                    {
                                        Vehicle vehicle = this.hostDevice.GetVehicle(shuttleID);
                                        if (vehicle != null && string.IsNullOrWhiteSpace(vehicle.CommandId))
                                        {
                                            isFull = false;
                                        }
                                    }
                                    if (isFull)
                                    {
                                        //当前指令所在出料CV绑定的轿厢已满，无法入料
                                        transferWorkItem.enableTransferIn = false;
                                    }
                                    else
                                    {
                                        transferWorkItem.enableTransferIn = true;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        ConveyorBuffer conveyorBuffer = this.hostDevice.GetConveyorBuffer(transferWorkItem.Source.Trim());
                        if (conveyorBuffer != null && conveyorBuffer.Floor > this.shuttleMaster.ShuttleFloor)
                        {
                            List<string> shuttles = conveyorBuffer.Shuttles;
                            foreach (string shuttleID in shuttles)
                            {
                                Vehicle vehicle = this.hostDevice.GetVehicle(shuttleID);
                                if (vehicle != null && string.IsNullOrWhiteSpace(vehicle.CommandId))
                                {
                                    isFull = false;
                                }
                            }
                            if (isFull)
                            {
                                //当前指令所在出料CV绑定的轿厢已满，无法入料
                                transferWorkItem.enableTransferIn = false;
                            }
                            else
                            {
                                transferWorkItem.enableTransferIn = true;
                            }
                        }
                    }
                }
                foreach (TransferWorkItem transferWorkItem in transferWorks)
                {
                    if (transferWorkItem.enableTransferIn)
                    {
                        ResultFull = false;
                    }
                }
            }
            return ResultFull;
        }
        public CimToPLCCommandInfo GetShuttleCommandFloor()
        {
            CimToPLCCommandInfo floor = new CimToPLCCommandInfo();
            if (JudgeShuttleOutIsFull())
            {
                return floor;
            }
            List<TransferWorkItem> transferWorks = this.hostDevice.LDispatcher.GetTransferCommandOnShuttle();
            if (this.shuttleMaster.DoNextCommand() == ShuttleNextCommandType.TRANSFEROUTWAIT)
            {
                foreach (TransferWorkItem transferWorkItem in transferWorks)
                {
                    LifterPort lifterPort = this.hostDevice.GetLifterPort(transferWorkItem.Dest);
                    if (lifterPort != null && lifterPort.Floor > floor.Floor && lifterPort.Floor != this.shuttleMaster.ShuttleFloor && lifterPort.LifterPortState != enumRIDState.DOWN && transferWorkItem.enableTransferOut)
                    {
                        floor.Floor = lifterPort.Floor;
                        floor.TransferWorkItem = transferWorkItem;
                    }
                }
            }
            else
            {
                foreach (TransferWorkItem transferWorkItem in transferWorks)
                {
                    LifterPort lifterPort = this.hostDevice.GetLifterPort(transferWorkItem.Dest);
                    if (lifterPort != null && lifterPort.Floor > floor.Floor && lifterPort.LifterPortState != enumRIDState.DOWN && transferWorkItem.enableTransferOut)
                    {
                        floor.Floor = lifterPort.Floor;
                        floor.TransferWorkItem = transferWorkItem;
                    }
                }
            }
            return floor;
        }
        /// <summary>
        /// 获取Loader的最高指令楼层
        /// </summary>
        /// <returns></returns>
        public CimToPLCCommandInfo GetLoaderHightFloor(List<TransferWorkItem> LoadREQCommand)
        {
            CimToPLCCommandInfo floor = new CimToPLCCommandInfo();
            //获取当前楼层及以下楼层，初始化指令的最高楼层
            foreach (TransferWorkItem transferWorkItem in LoadREQCommand)
            {
                LifterPort lifterPort = this.hostDevice.GetLifterPort(transferWorkItem.Source.Trim());
                if (lifterPort != null)
                {
                    if (lifterPort.Floor > floor.Floor && lifterPort.LifterPortState != enumRIDState.DOWN)
                    {
                        floor.Floor = lifterPort.Floor;
                        floor.TransferWorkItem = transferWorkItem;
                    }
                }
                else
                {
                    ConveyorBuffer conveyorBuffer = this.hostDevice.GetConveyorBuffer(transferWorkItem.Source.Trim());
                    if (conveyorBuffer != null && conveyorBuffer.Floor > floor.Floor && conveyorBuffer.InService)
                    {
                        floor.Floor = conveyorBuffer.Floor;
                        floor.TransferWorkItem = transferWorkItem;
                    }
                }
            }
            return floor;
        }
        /// <summary>
        /// add by yangshl 2023/9/14
        /// 轿厢不在1F，且轿厢内有物料,返回指令楼层
        /// </summary>
        /// <param name="isFull"></param>
        /// <returns>返回指令楼层</returns>
        private CimToPLCCommandInfo GetMoveCommandByShuttleMode(bool isFull)
        {
            CimToPLCCommandInfo floor = new CimToPLCCommandInfo();
            //如果接料轿厢都是满状态，返回轿厢内指令最高楼层
            if (isFull)
            {
                //if (JudgeShuttleOutIsFull())
                //{
                //    floor.Floor = this.shuttleMaster.ShuttleFloor;
                //    return floor;
                //}
                //else
                //{
                //    floor = this.GetShuttleCommandFloor();
                //}
                floor = this.GetShuttleCommandFloor();
            }
            else
            {
                //获取LoadREQ指令
                List<TransferWorkItem> loadWorks = this.GetTransferCommandByStatus(enumTransferState.LOADREQ);
                //有LoadREQ指令
                if (loadWorks.Count > 0)
                {
                    //获取当前楼层及以下楼层的超时指令
                    List<TransferWorkItem> transferTimeOuts = new List<TransferWorkItem>();
                    foreach (TransferWorkItem transferWork in loadWorks)
                    {
                        LifterPort lifterPort = this.hostDevice.GetLifterPort(transferWork.Source.Trim());
                        if (lifterPort != null)
                        {
                            if (lifterPort.Floor <= this.shuttleMaster.ShuttleFloor && transferWork.CommandTimeOutFlag)
                            {
                                transferTimeOuts.Add(transferWork);
                            }
                        }
                        else
                        {
                            ConveyorBuffer conveyorBuffer = this.hostDevice.GetConveyorBuffer(transferWork.Source.Trim());
                            if (conveyorBuffer  != null)
                            {
                                if (conveyorBuffer.Floor <= this.shuttleMaster.ShuttleFloor && transferWork.CommandTimeOutFlag)
                                {
                                    transferTimeOuts.Add(transferWork);
                                }
                            }
                        }
                    }
                    //判断是否有超时指令，有超时指令，返回超时指令和轿厢内指令的最高楼层
                    if (transferTimeOuts.Count > 0)
                    {
                        CimToPLCCommandInfo timeOutCommndFloor = new CimToPLCCommandInfo();
                        CimToPLCCommandInfo shuttleCommndFloor = new CimToPLCCommandInfo();
                        //获取超时指令的最高楼层
                        foreach (TransferWorkItem transferWork in transferTimeOuts)
                        {
                            LifterPort lifterPort = this.hostDevice.GetLifterPort(transferWork.Source.Trim());
                            if (lifterPort != null)
                            {
                                if (lifterPort.Floor > floor.Floor && lifterPort.LifterPortState != enumRIDState.DOWN && transferWork.enableTransferIn)
                                {
                                    timeOutCommndFloor.Floor = lifterPort.Floor;
                                    timeOutCommndFloor.TransferWorkItem = transferWork;
                                }
                            }
                            else
                            {
                                ConveyorBuffer conveyorBuffer = this.hostDevice.GetConveyorBuffer(transferWork.Source.Trim());
                                if (conveyorBuffer != null)
                                {
                                    if (conveyorBuffer.Floor > floor.Floor && conveyorBuffer.InService && transferWork.enableTransferIn)
                                    {
                                        timeOutCommndFloor.Floor = conveyorBuffer.Floor;
                                        timeOutCommndFloor.TransferWorkItem = transferWork;
                                    }
                                }
                            }
                        }
                        //获取轿厢内指令的最高楼层
                        shuttleCommndFloor = this.GetShuttleCommandFloor();

                        //返回超时指令跟轿厢内指令最高楼层
                        if (shuttleCommndFloor.Floor >= timeOutCommndFloor.Floor)
                        {
                            floor = shuttleCommndFloor;
                        }
                        else
                        {
                            floor = timeOutCommndFloor;
                        }
                    }
                    else//没有超时指令,返回初始化指令和轿厢内指令的最高楼层
                    {
                        //判断当前楼层及以下楼层是否有LoadREQ指令
                        List<TransferWorkItem> LoadREQCommand = new List<TransferWorkItem>();
                        foreach (TransferWorkItem transferWork in loadWorks)
                        {
                            LifterPort lifterPort = this.hostDevice.GetLifterPort(transferWork.Source.Trim());
                            if (lifterPort != null)
                            {
                                if (lifterPort.Floor <= this.shuttleMaster.ShuttleFloor && !transferWork.CommandTimeOutFlag && transferWork.enableTransferIn)
                                {
                                    LoadREQCommand.Add(transferWork);
                                }
                            }
                            else
                            {
                                ConveyorBuffer conveyorBuffer = this.hostDevice.GetConveyorBuffer(transferWork.Source.Trim());
                                if (conveyorBuffer != null)
                                {
                                    if (conveyorBuffer.Floor <= this.shuttleMaster.ShuttleFloor && !transferWork.CommandTimeOutFlag && transferWork.enableTransferIn)
                                    {
                                        LoadREQCommand.Add(transferWork);
                                    }
                                }
                            }
                        }
                        CimToPLCCommandInfo LoadCommandFloor = new CimToPLCCommandInfo();
                        CimToPLCCommandInfo shuttleCommandFloor = new CimToPLCCommandInfo();
                        //获取当前楼层及以下楼层，初始化指令的最高楼层
                        LoadCommandFloor = this.GetLoaderHightFloor(LoadREQCommand);
                        //返回轿厢内的最高楼层
                        shuttleCommandFloor = this.GetShuttleCommandFloor();
                        if (shuttleCommandFloor.Floor >= LoadCommandFloor.Floor)
                        {
                            floor = shuttleCommandFloor;
                        }
                        else
                        {
                            floor = LoadCommandFloor;
                        }
                    }
                }
                else//没有LoadREQ指令,返回轿厢内指令最高楼层
                {
                    floor = this.GetShuttleCommandFloor();
                }
            }
            return floor;
        }
        /// <summary>
        /// add by yangshl 2023/9/13
        /// 执行轿厢master移动指令
        /// </summary>
        public void DoFirstMoveCommand()
        {
            //判断设备状态
            if (!this.JudgeEquipmentTransferStatus())
            {
                this.refreshCommandTimer.Start();
                return;
            }
            //创建轿厢Move指令
            CimToPLCCommandInfo cimToPLCCommandInfo = this.CreateShuttleMoveCommand();
            //判断返回的楼层是否为0层
            if (cimToPLCCommandInfo.Floor == 0)
            {
                //Timer监测开始
                this.refreshCommandTimer.Start();
            }
            else
            {
                //执行Move指令逻辑，判断创建的Move指令跟轿厢是否位于同一楼层
                if (cimToPLCCommandInfo.Floor == this.shuttleMaster.ShuttleFloor)
                {
                    //判断是否能执行transfer指令
                    //this.shuttleMaster.JudgeDoNextCommand();
                    this.shuttleMaster.DoShuttleTransfer();
                }
                else//给PLC下move指令
                {
                    this.shuttleMaster.DoShuttleMasterMove(cimToPLCCommandInfo);
                }
            }
        }
        /// <summary>
        /// add by yangshl 2023/10/08
        /// 判断设备传输状态，设备是Pause，或设备状态为Down则不下指令。
        /// </summary>
        /// <returns></returns>
        public bool JudgeEquipmentTransferStatus()
        {
            bool equipmentStatus = false;
            if (this.hostDevice.DeviceState != enumRIDState.DOWN && this.hostDevice.SCStatemode == enumSCStateMode.SC_AUTO)
            {
                equipmentStatus = true;
            }
            return equipmentStatus;
        }
        /// <summary>
        /// add by yangshl 2023/9/12
        /// 轿厢在1F或者轿厢内指令为空
        /// </summary>
        /// <returns>返回轿厢目的地楼层</returns>
        private CimToPLCCommandInfo Floor1FOrShuttleIsEmpty()
        {
            CimToPLCCommandInfo floor = new CimToPLCCommandInfo();
            if (this.shuttleMaster.DoNextCommand()==ShuttleNextCommandType.TRANSFEROUTWAIT&&this.JudgeShuttleIsFull1F())
            {
                return this.GetShuttleCommandFloor();
            }
            CimToPLCCommandInfo ShuttleExistCommandFloor = new CimToPLCCommandInfo(); 
            CimToPLCCommandInfo LoadREQCommandFloor = new CimToPLCCommandInfo();
            ShuttleExistCommandFloor = this.ShuttleExistCommand();
            LoadREQCommandFloor = this.LoadREQCommand();
            //比较两个楼层，获取最大的楼层
            if (ShuttleExistCommandFloor.Floor >= LoadREQCommandFloor.Floor)
            {
                floor = ShuttleExistCommandFloor;
            }
            else
            {
                floor = LoadREQCommandFloor;
            }
            return floor;
        }
        /// <summary>
        /// add by yangshl  2023/9/13
        /// 判断轿厢内有无指令，无指令返回0层，有指令，返回指令的最高楼层
        /// </summary>
        /// <returns>返回楼层</returns>
        private CimToPLCCommandInfo ShuttleExistCommand()
        {
            CimToPLCCommandInfo floor = new CimToPLCCommandInfo();
            //轿厢内无指令，返回0层
            if (shuttleMaster.ShuttleIsEmpty())
            {
                floor.Floor = 0;
            }
            else//轿厢内有指令，返回指令的最高楼层
            {
                floor = this.GetShuttleCommandFloor();
            }
            return floor;
        }
        /// <summary>
        /// add by yangshl 2023/9/13
        /// 判断有无初始化指令，
        ///  --无初始化指令返回0层
        ///  --有初始化指令：
        ///      1.判断有无超时指令：返回超时指令的最高楼层
        ///      2.无超时指令：
        ///          -1.1F没有接料指令：返回所有接料指令的最高楼层
        ///          -2.1F有接料指令，当前楼层及以下楼层有接料指令：返回当前楼层及以下楼层指令的最高楼层
        ///          -3.1F有接料指令，当前楼层及以下楼层没有接料指令：返回1F楼层
        /// </summary>
        /// <returns>返回楼层</returns>
        private CimToPLCCommandInfo LoadREQCommand()
        {
            CimToPLCCommandInfo floor = new CimToPLCCommandInfo();
            //获取所有LoadREQ指令
            List<TransferWorkItem> transferWorks = this.hostDevice.LDispatcher.GetTransferCommandByStatus(enumTransferState.LOADREQ);
            //无LoadREQ指令Case
            if (transferWorks.Count <= 0)
            {
                return floor;
            }
            else
            {
                List<TransferWorkItem> transferTimeOuts = new List<TransferWorkItem>();
                foreach (TransferWorkItem transferWork in transferWorks)
                {
                    if (transferWork.CommandTimeOutFlag)
                    {
                        transferTimeOuts.Add(transferWork);
                    }
                }
                //判断是否有超时指令
                if (transferTimeOuts.Count > 0)
                {
                    //比较超时指令的楼层，返回最高楼层
                    foreach (TransferWorkItem transferWork in transferTimeOuts)
                    {
                        LifterPort lifterPort = this.hostDevice.GetLifterPort(transferWork.Source.Trim());
                        if (lifterPort != null)
                        {
                            if (lifterPort.Floor > floor.Floor && lifterPort.LifterPortState != enumRIDState.DOWN)
                            {
                                floor.Floor = lifterPort.Floor;
                                floor.TransferWorkItem = transferWork;
                            }
                        }
                        else
                        {
                            ConveyorBuffer conveyorBuffer = this.hostDevice.GetConveyorBuffer(transferWork.Source.Trim());
                            if (conveyorBuffer != null)
                            {
                                if (conveyorBuffer.Floor > floor.Floor && conveyorBuffer.InService)
                                {
                                    floor.Floor = conveyorBuffer.Floor;
                                    floor.TransferWorkItem = transferWork;
                                }
                            }
                        }
                    }
                }
                else//无超时指令，再判断LoadREQ指令
                {
                    bool commandOn1F = false;
                    //1F是否有LoadREQ指令
                    foreach (TransferWorkItem transferWork in transferWorks)
                    {
                        LifterPort lifterPort = this.hostDevice.GetLifterPort(transferWork.Source.Trim());
                        if (lifterPort != null)
                        {
                            if (lifterPort.Floor == 10)
                            {
                                commandOn1F = true;
                            }
                        }
                        else
                        {
                            ConveyorBuffer conveyorBuffer = this.hostDevice.GetConveyorBuffer(transferWork.Source.Trim());
                            if (conveyorBuffer != null)
                            {
                                if (conveyorBuffer.Floor == 10)
                                {
                                    commandOn1F = true;
                                }
                            }
                        }
                    }
                    //1F有指令Case
                    if (commandOn1F)
                    {
                        //获取当前楼层及以下楼层指令
                        List<TransferWorkItem> underFloorCommands = new List<TransferWorkItem>();
                        foreach (TransferWorkItem transferWork in transferWorks)
                        {
                            LifterPort lifterPort = this.hostDevice.GetLifterPort(transferWork.Source.Trim());
                            if (lifterPort != null)
                            {
                                if (lifterPort.Floor <= shuttleMaster.ShuttleFloor)
                                {
                                    underFloorCommands.Add(transferWork);
                                }
                            }
                            else
                            {
                                ConveyorBuffer conveyorBuffer = this.hostDevice.GetConveyorBuffer(transferWork.Source.Trim());
                                if (conveyorBuffer != null)
                                {
                                    if (conveyorBuffer.Floor <= shuttleMaster.ShuttleFloor)
                                    {
                                        underFloorCommands.Add(transferWork);
                                    }
                                }
                            }
                        }
                        //当前楼层及以下楼层有指令
                        if (underFloorCommands.Count > 0)
                        {
                            foreach (TransferWorkItem transferWork in underFloorCommands)
                            {
                                LifterPort lifterPort = this.hostDevice.GetLifterPort(transferWork.Source.Trim());
                                if (lifterPort != null)
                                {
                                    if (lifterPort.Floor > floor.Floor && lifterPort.LifterPortState != enumRIDState.DOWN)
                                    {
                                        floor.Floor = lifterPort.Floor;
                                        floor.TransferWorkItem = transferWork;
                                    }
                                }
                                else
                                {
                                    ConveyorBuffer conveyorBuffer = this.hostDevice.GetConveyorBuffer(transferWork.Source.Trim());
                                    if (conveyorBuffer != null)
                                    {
                                        if (conveyorBuffer.Floor > floor.Floor && conveyorBuffer.InService)
                                        {
                                            floor.Floor = conveyorBuffer.Floor;
                                            floor.TransferWorkItem = transferWork;
                                        }
                                    }
                                }
                            }
                        }
                        else//当前楼层及以下楼层没有指令
                        {
                            floor.Floor = 10;
                        }
                    }
                    else//1F没有指令
                    {
                        //比较所有LoadREQ指令的楼层，返回最高楼层
                        foreach (TransferWorkItem transferWork in transferWorks)
                        {
                            LifterPort lifterPort = this.hostDevice.GetLifterPort(transferWork.Source.Trim());
                            if (lifterPort != null)
                            {
                                if (lifterPort.Floor > floor.Floor && lifterPort.LifterPortState != enumRIDState.DOWN)
                                {
                                    floor.Floor = lifterPort.Floor;
                                    floor.TransferWorkItem = transferWork;
                                }
                            }
                            else
                            {
                                ConveyorBuffer conveyorBuffer = this.hostDevice.GetConveyorBuffer(transferWork.Source.Trim());
                                if (conveyorBuffer != null)
                                {
                                    if (conveyorBuffer.Floor > floor.Floor && conveyorBuffer.InService)
                                    {
                                        floor.Floor = conveyorBuffer.Floor;
                                        floor.TransferWorkItem = transferWork;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return floor;
        }
        /// <summary>
        /// add by yangshl 2023/10/08
        /// 获取不在Down楼层的所有指令
        /// </summary>
        /// <param name="transferWorkItems"></param>
        /// <returns></returns>
        public List<TransferWorkItem> GetNotDownCommandByFloor(List<TransferWorkItem> transferWorkItems)
        {
            //定义Down的port口所在楼层集合
            List<int> downFloor = new List<int>();
            List<TransferWorkItem> transferWorks = new List<TransferWorkItem>();
            //获取所有Down的楼层
            foreach (LifterPort lifterPort in this.hostDevice.LifterPorts.Values)
            {
                if (lifterPort.LifterPortState == enumRIDState.DOWN)
                {
                    if (!downFloor.Contains(lifterPort.Floor))
                    {
                        downFloor.Add(lifterPort.Floor);
                    }
                }
            }
            foreach (TransferWorkItem transferWorkItem in transferWorkItems)
            {
                LocationUnit locationUnit = this.hostDevice.GetLocationUnit(transferWorkItem.Source);
                if (locationUnit is LifterPort)
                {
                    LifterPort lifterPort = (LifterPort)locationUnit;
                    if (!downFloor.Contains(lifterPort.Floor))
                    {
                        transferWorks.Add(transferWorkItem);
                    }
                }
                if (locationUnit is ConveyorBuffer)
                {
                    ConveyorBuffer conveyorBuffer = (ConveyorBuffer)locationUnit;
                    LifterPort lifterPort = this.hostDevice.GetLifterPort(conveyorBuffer.LifterPortID);
                    if (!downFloor.Contains(lifterPort.Floor))
                    {
                        transferWorks.Add(transferWorkItem);
                    }
                }
            }
            return transferWorks;
        }
        /// <summary>
        /// add by yangshl 2023/9/12
        /// 根据传入的指令状态,获取指令相应的指令集合
        /// </summary>
        /// <returns>返回指令集合</returns>
        public List<TransferWorkItem> GetTransferCommandByStatus(enumTransferState commandStatus)
        {
            List<TransferWorkItem> workItemsByStatus = new List<TransferWorkItem>();
            if (this.workList != null && this.workList.Count > 0)
            {
                lock (this.workList_monitor)
                {
                    foreach (TransferWorkItem transferWork in workList)
                    {
                        //根据传入的指令状态，筛选指令存入集合
                        if (transferWork.TransferState == commandStatus)
                        {
                            workItemsByStatus.Add(transferWork);
                        }
                    }
                }
            }
            /*            if (commandStatus == enumTransferState.LOADREQ)
                        {
                            workItemsByStatus = this.GetNotDownCommandByFloor(workItemsByStatus);
                        }*/
            return workItemsByStatus;
        }
        public List<TransferWorkItem> GetTransferCommandOnShuttle()
        {
            List<TransferWorkItem> workItemsOnShuttle = new List<TransferWorkItem>();
            if (this.workList != null && this.workList.Count > 0)
            {
                lock (this.workList_monitor)
                {
                    foreach (TransferWorkItem transferWork in workList)
                    {
                        //在轿厢内的指令
                        if (transferWork.IsOnShuttle)
                        {
                            workItemsOnShuttle.Add(transferWork);
                        }
                    }
                }
            }
            return workItemsOnShuttle;
        }
        #endregion
        protected void CheckingTransferWork()
        {
            if (this.workList.Count > 0)
            {
                Thread.Sleep(600);
                this.keepWorking = true;
            }
            else
            {
                this.keepWorking = false;
            }
        }
        /// <summary>
        /// 创建Carrier的搬送指令，并加指令集合
        /// </summary>
        /// <param name="carrierID">物料ID</param>
        /// <param name="destPort">目的地</param>
        /// <param name="xNextLoc"></param>
        public void AddNewTransferQueue(string carrierID, string destPort, string SrcPort)
        {
            //获取物料对象
            Carrier carrier = Naming.GetCarrierManager().GetCarrier(carrierID);
            if (carrier == null)
            {
                LogHelper.loggerInfo("在[AddNewTransferQueue]方法中，创建物料指令时，物料信息为空");
                return;
            }
            //获取起始地
            //当前位置为起始地
            //LifterPort lifterPortByLoc = this.hostDevice.GetLifterPort(carrier.CarrierLoc);
            //inputPort为起始地
            LifterPort lifterPortSrc = this.hostDevice.GetLifterPort(SrcPort);
            if (lifterPortSrc == null)
            {
                //记录Log日志，或弹窗提醒
                LogHelper.loggerInfo("方法名：AddNewTransferQueue，报错：lifterPortSrc为空");
                Console.WriteLine("方法名：AddNewTransferQueue，报错：lifterPortSrc为空");
                return;
            }
            else
            {
                string strDesc = "";
                //验证指令是否有效
                enumNewTrasferCmdAvailable checkResult = this.hostDevice.CheckNewTrasferCmdAvailable(carrierID, carrier.CarrierLoc, destPort, out strDesc);
                if (checkResult == enumNewTrasferCmdAvailable.AVAIL)
                {
                    TransferWorkItem transferWorkItem = new TransferWorkItem();
                    transferWorkItem.CommandID = "M" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "-" + carrierID;
                    transferWorkItem.CarrierID = carrierID;
                    transferWorkItem.LotID = carrier.LotID;
                    try
                    {
                        transferWorkItem.Priority = Convert.ToInt32(lifterPortSrc.PortPriority);
                    }
                    catch (Exception)
                    {
                        transferWorkItem.Priority = 0;
                    }
                    transferWorkItem.CarrierType = carrier.CarrierType;
                    transferWorkItem.Source = this.hostDevice.GetUnitHostID(carrier.CarrierLoc);
                    transferWorkItem.Dest = destPort;
                    transferWorkItem.CarrierLoc = carrier.CarrierLoc;
                    transferWorkItem.FromPLCID = this.hostDevice.ConvertHostIDtoPlcID(transferWorkItem.Source);
                    transferWorkItem.ToPLCID = this.hostDevice.ConvertHostIDtoPlcID(destPort);
                    transferWorkItem.NextLocation = "";
                    transferWorkItem.TransferState = enumTransferState.CREATE;
                    transferWorkItem.CreateCommandTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    transferWorkItem.UpdateCommandTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                    transferWorkItem.CreateCommandType = SysTemConstant.CreateCommandType.AUTO.ToString();
                    transferWorkItem.CommandType = TransferCommandType.TRANSFER;
                    carrier.CommandID = transferWorkItem.CommandID;
                    carrier.Update();
                    MaterialInfoControl.materialInfoControl.UpdateDelegate();
                    //上报Host OperatorInitiatedAction事件
                    this.hostDevice.SecsDriver.SendMessage("S6F11", "602", transferWorkItem);

                    //给PLC物料启动信号
                    if (lifterPortSrc.IsCombine)
                    {
                        ConveyorBuffer conveyorBuffer = this.hostDevice.GetConveyorBuffer(carrier.CarrierLoc);
                        if (conveyorBuffer != null)
                        {
                            conveyorBuffer._I_MATERIALRUNREQ = true;
                        }
                        else
                        {
                            //记录Log日志，或弹窗提醒（创建指令时，物料当前位置为空）
                            LogHelper.loggerInfo("PC自动创建指令时，物料当前位置为空");
                        }
                    }
                    else
                    {
                        lifterPortSrc._I_MATERIALRUNREQ = true;
                    }
                    int result = this.RequestJob(transferWorkItem);
                    if (result > 0)
                    {
                        LogHelper.loggerInfo(string.Format("PC自动创建指完成，指令ID为:{0}", transferWorkItem.CommandID));
                    }
                    else
                    {
                        LogHelper.loggerInfo(string.Format("PC自动创建指令失败，指令ID为:{0}", transferWorkItem.CommandID));
                    }

                }
                else
                {
                    //Log日志记录，弹窗
                    LogHelper.loggerInfo("PC自动创建物料指令时，验证指令结果为：" + checkResult + "; 描述：" + strDesc);
                    Console.WriteLine(strDesc);
                }
            }
        }
        /// <summary>
        /// 手动创建Carrier的搬送指令，并加指令集合
        /// </summary>
        /// <param name="carrierID">物料ID</param>
        /// <param name="destPort">目的地</param>
        /// <param name="xNextLoc"></param>
        public string AddTransferQueueManual(string carrierID, string from, string dest, out string Description)
        {
            Description = "";
            Carrier carrier = Naming.GetCarrierManager().GetCarrier(carrierID);

            if (carrier == null)
            {
                LogHelper.loggerInfo("在[AddTransferQueueManual]方法中，创建物料指令时，物料信息为空");
                Description = "创建物料指令时，物料信息为空";
                return "";
            }

            TransferWorkItem transferWorkItem = new TransferWorkItem();
            transferWorkItem.CommandID =  "M" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "-" + carrierID;
            transferWorkItem.CarrierID = carrierID;

            transferWorkItem.CarrierType = carrier.CarrierType;
            transferWorkItem.Source = from;
            transferWorkItem.Dest = dest;
            transferWorkItem.CarrierLoc = carrier.CarrierLoc;
            transferWorkItem.FromPLCID = this.hostDevice.ConvertHostIDtoPlcID(transferWorkItem.Source);
            transferWorkItem.ToPLCID = this.hostDevice.ConvertHostIDtoPlcID(dest);
            transferWorkItem.TransferState = enumTransferState.CREATE;
            transferWorkItem.CreateCommandTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            transferWorkItem.UpdateCommandTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            transferWorkItem.CreateCommandType = SysTemConstant.CreateCommandType.MANUAL.ToString();
            transferWorkItem.CommandType = TransferCommandType.TRANSFER;
            carrier.CommandID = transferWorkItem.CommandID;
            carrier.Update();
            MaterialInfoControl.materialInfoControl.UpdateDelegate();
            this.hostDevice.SecsDriver.SendMessage("S6F11", "602", transferWorkItem);

            LifterPort lifterPortTemp = null;
            ConveyorBuffer conveyorBuffer = null;
            LifterPort lifterPortSrc = this.hostDevice.GetLifterPort(transferWorkItem.Source);
            ConveyorBuffer conveyorBufferSrc = this.hostDevice.GetConveyorBuffer(transferWorkItem.Source);
            if (lifterPortSrc != null)
            {
                lifterPortTemp = lifterPortSrc;
            }
            else if (conveyorBufferSrc != null)
            {
                lifterPortTemp = this.hostDevice.GetLifterPort(conveyorBufferSrc.LifterPortID);
            }
            else
            {
                LogHelper.loggerInfo("在[AddNewTransferQueue]方法中，创建物料指令时，选择的起始地不符合");
                Description = "创建物料指令时，选择的起始地不符合";
                return "";
            }
            if (lifterPortTemp.IsCombine)
            {
                conveyorBuffer = this.hostDevice.GetConveyorBuffer(carrier.CarrierLoc);
                if (conveyorBuffer != null)
                {
                    conveyorBuffer._I_MATERIALRUNREQ = true;
                }
                else
                {
                    //记录Log日志，或弹窗提醒（创建指令时，物料当前位置为空）
                    LogHelper.loggerInfo($"手动创建指令时，物料[{carrier.CarrierId}]当前位置[{carrier.CarrierLoc}]不正确");
                }
            }
            else
            {
                lifterPortTemp._I_MATERIALRUNREQ = true;
            }
            try
            {
                transferWorkItem.Priority = Convert.ToInt32(lifterPortTemp.PortPriority);
            }
            catch (Exception)
            {
                transferWorkItem.Priority = 0;
            }
            int result = this.RequestJob(transferWorkItem);
            if (result > 0)
            {
                LogHelper.loggerInfo(string.Format("手动创建指完成，指令ID为:{0}", transferWorkItem.CommandID));
            }
            else
            {
                return "";
            }
            return transferWorkItem.CommandID;
        }
        /// <summary>
        /// 快捷方式创建指令
        /// </summary>
        /// <returns></returns>
        public string AddTransferQueueByShortcut(out string desc)
        {
            string commandID = "";
            desc = "";
            bool flag = false;
            string carrierID = "";
            string source = this.ShortcutCreateCommandSource.Trim();
            string dest = this.ShortcutCreateCommandDest.Trim();

            //判断起始地或目的地是否合法
            bool judgefFlag = this.JudgeSourceOrDestIsEnableByShortcutCommand(source,dest,out desc);

            if (!judgefFlag)
            {
                LogHelper.loggerInfo(desc);
                return commandID;
            }
            //判断起始地是否有物料
            //  1.有物料：直接创建指令并绑定物料
            //  2.无物料：弹出创建指令界面
            LocationUnit locationUnit = this.hostDevice.GetLocationUnit(source);
            if (locationUnit != null)
            {
                if (locationUnit is LifterPort)
                {
                    LifterPort lifterPort = (LifterPort)locationUnit;
                    if ((lifterPort.CarrierPresence[1] && !string.IsNullOrEmpty(lifterPort.CarrierId)))
                    {
                        flag = true;
                        carrierID = lifterPort.CarrierId;
                    }
                    
                }
                else if (locationUnit is ConveyorBuffer)
                {
                    ConveyorBuffer conveyorBuffer = (ConveyorBuffer)locationUnit;
                    if ((conveyorBuffer.CstPresence && !string.IsNullOrEmpty(conveyorBuffer.CSTID)))
                    {
                        flag = true;
                        carrierID = conveyorBuffer.CSTID;
                    }
                }
                else
                {
                    desc = $"快捷方式创建指令时，起始地[{source}]不正确";
                    LogHelper.loggerInfo($"快捷方式创建指令时，起始地[{source}]不正确");
                    return commandID;
                }
            }
            else
            {
                desc = $"快捷方式创建指令时，起始地为空";
                LogHelper.loggerInfo($"快捷方式创建指令时，起始地为空");
                return commandID;
            }

            //如果起始地有物料
            if (flag)
            {
                enumNewTrasferCmdAvailable checkResult = this.hostDevice.CheckNewTrasferCmdManual(carrierID, source, dest, out desc);
                if (checkResult == enumNewTrasferCmdAvailable.AVAIL)
                {
                    TransferWorkItem transferWorkItem = this.hostDevice.LDispatcher.GetJobByCarrierID(carrierID);
                    if (transferWorkItem == null)
                    {
                        commandID = this.AddTransferQueueManual(carrierID, source, dest, out desc);
                    }
                    else
                    {
                        desc = ($"手动快捷方式创建物料[{carrierID}]指令时,指令[{transferWorkItem.CommandID}]已存在");
                        LogHelper.loggerInfo($"手动快捷方式创建物料[{carrierID}]指令时,指令[{transferWorkItem.CommandID}]已存在");
                    }
                }
                
            }
            else
            {
                desc = $"快捷方式创建指令时，起始地物料为空";
                LogHelper.loggerInfo($"快捷方式创建指令时，起始地物料为空");
            }
            return commandID;
        }
        /// <summary>
        /// 判断起始地或目的地是否合法
        /// 判断起始地或目的地方向是否合法
        /// </summary>
        private bool JudgeSourceOrDestIsEnableByShortcutCommand(string source, string dest, out string desc)
        {
            bool flag = true;
            desc = "";
            LocationUnit sourceLocationUnit = this.hostDevice.GetLocationUnit(source);
            LocationUnit destLocationUnit = this.hostDevice.GetLocationUnit(dest);

            //判断起始地是否合法
            if (sourceLocationUnit is LifterPort)
            {
                LifterPort sourceLifterPort = (LifterPort)sourceLocationUnit;
                if (sourceLifterPort.portInOutMode != enumLifterPortDirection.IN )
                {
                    desc = $"起始地[{source}]方向不正确，请检查！！";
                    flag = false;
                }
            }
            else if (sourceLocationUnit is ConveyorBuffer)
            {
                ConveyorBuffer conveyorBuffer = (ConveyorBuffer)sourceLocationUnit;
                if (!ConveyorBuffer.Constants.CVUNLOAD.Equals(conveyorBuffer.Cvtype))
                {
                    desc = $"起始地[{source}]方向不正确，请检查！！";
                    flag = false;
                }
            }

            //判断目的地是否合法
            if (destLocationUnit is LifterPort)
            {
                LifterPort destLifterPort = (LifterPort)destLocationUnit;
                if (destLifterPort.portInOutMode != enumLifterPortDirection.OUT)
                {
                    desc = $"目的地[{dest}]方向不正确，请检查！！";
                    flag = false;
                }
            }
            else if (destLocationUnit is ConveyorBuffer)
            {
                ConveyorBuffer destBuffer = (ConveyorBuffer)destLocationUnit;
                if (!ConveyorBuffer.Constants.CVLOAD.Equals(destBuffer.Cvtype))
                {
                    desc = $"目的地[{dest}]方向不正确，请检查！！";
                    flag = false;
                }
            }
            return flag;
        }
        /// <summary>
        /// 判断目的地是否符合标准
        /// </summary>
        /// <param name="carrierID"></param>
        /// <param name="destPort"></param>
        /// <param name="xNextLoc"></param>
        /// <param name="LotID"></param>
        public string SoureceIsEnable(string source)
        {
            string resukt = this.hostDevice.GetUnitHostID(source);
            return resukt;
        }
        public void AddNewTransferQueue(TransferWorkItem workItem)
        {
            if (workItem != null)
            {
                workItem.FromPLCID = this.hostDevice.ConvertHostIDtoPlcID(workItem.Source);
                workItem.ToPLCID = this.hostDevice.ConvertHostIDtoPlcID(workItem.Dest);
                workItem.TransferState = enumTransferState.CREATE;
                workItem.CreateCommandTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                workItem.UpdateCommandTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                workItem.CreateCommandType = SysTemConstant.CreateCommandType.AUTO.ToString();
                workItem.CommandType = TransferCommandType.TRANSFER;
                string resultDesc = "";
                enumNewTrasferCmdAvailable checkResult = this.hostDevice.CheckNewTrasferCmdAvailable(workItem.CarrierID, workItem.Source, workItem.Dest, out resultDesc);
                if (checkResult == enumNewTrasferCmdAvailable.AVAIL)
                {
                    LifterPort lifterPort = null;
                    ConveyorBuffer conveyorBuffer = null;
                    LifterPort lifterPortSrc = this.hostDevice.GetLifterPort(workItem.Source);
                    ConveyorBuffer conveyorBufferSrc = this.hostDevice.GetConveyorBuffer(workItem.Source);
                    if (lifterPortSrc != null)
                    {
                        lifterPort = lifterPortSrc;
                    }
                    if (conveyorBufferSrc != null)
                    {
                        conveyorBuffer = conveyorBufferSrc;
                        lifterPort = this.hostDevice.GetLifterPort(conveyorBuffer.LifterPortID);
                    }
                    //给PLC物料启动信号
                    if (lifterPort.IsCombine)
                    {
                        if (conveyorBuffer != null)
                        {
                            conveyorBuffer._I_MATERIALRUNREQ = true;
                        }
                        else
                        {
                            //记录Log日志，或弹窗提醒（创建指令时，物料当前位置为空）
                            LogHelper.loggerInfo("HOST创建指令时，物料当前位置为空");
                        }
                    }
                    else
                    {
                        lifterPort._I_MATERIALRUNREQ = true;
                    }
                    int result = this.RequestJob(workItem);
                    if (result > 0)
                    {
                        LogHelper.loggerInfo(string.Format("HOST创建指令完成，指令ID为:{0}", workItem.CommandID));
                    }
                    else
                    {
                        LogHelper.loggerInfo(string.Format("HOST创建指令失败，指令ID为:{0}", workItem.CommandID));
                    }
                }
                else
                {
                    //Log日志记录，弹窗
                    LogHelper.loggerInfo("HOST创建物料指令时，验证指令结果为：" + checkResult + "; 描述：" + resultDesc);
                    workItem = null;
                }
            }
        }
        public TransferWorkItem GetJob(string commandId)
        {
            TransferWorkItem result;
            lock (this.workList_monitor)
            {
                foreach (TransferWorkItem current in this.workList)
                {
                    if (current.CommandID == commandId)
                    {
                        result = current;
                        return result;
                    }
                }
            }
            result = null;
            return result;
        }
        public TransferWorkItem[] GetWorkList()
        {
            TransferWorkItem[] array = new TransferWorkItem[this.workList.Count];
            this.workList.CopyTo(array);
            return array;
        }
        public TransferWorkItem GetJobByCarrierID(string carrierId)
        {
            TransferWorkItem result;
            lock (this.workList_monitor)
            {
                foreach (TransferWorkItem current in this.workList)
                {
                    if (current.CarrierID.Equals(carrierId))
                    {
                        result = current;
                        return result;
                    }
                }
            }
            result = null;
            return result;
        }
        public int RequestJob(TransferWorkItem workItem)
        {
            lock (this.workList_monitor)
            {
                workItem.DelayTimeCount = 1;
                workItem.QueueDeleyTimeCount = 1;
                int result =  workItem.Add();
                if (result > 0)
                {
                    this.workList.Add(workItem);
                    this.InnerPublishEvent(workItem.CommandID, TransferEvent.TransferEventType.ADD_TRANSFER);

                    //更新指令的传输状态
                    workItem.TransferState = enumTransferState.TRANSFERRING;
                }
                return result;
            }
            //this.Wakeup();
        }
        public void CompleteJob(string commandId, enumTransferResult trResult)
        {
            TransferWorkItem job = this.GetJob(commandId);
            lock (this.workList_monitor)
            {
                if (job != null)
                {
                    job.ResultCode = trResult;
                    job.TransferState = enumTransferState.COMPLETED;
                    this.InnerPublishEvent(job.CommandID, TransferEvent.TransferEventType.REMOVE_TRANSFER);
                    this.RemoveWork(job);
                }
            }
        }
        public void AbortCompleteJob(string commandId)
        {
            TransferWorkItem job = this.GetJob(commandId);
            lock (this.workList_monitor)
            {
                if (job != null)
                {
                    job.ResultCode = enumTransferResult.CANCEL;
                    this.InnerPublishEvent(job.CommandID, TransferEvent.TransferEventType.REMOVE_TRANSFER);
                    this.RemoveWork(job);
                }
            }
        }
        public void RemoveWork(TransferWorkItem workItem)
        {
            lock (this.workList_monitor)
            {
                this.workList.Remove(workItem);
                //删除指令表中的数据
                workItem.Delete();
                LogHelper.loggerInfo(string.Format("删除指令信息，指令ID:[{0}],指令状态:[{1}],指令结果:[{2}]", workItem.CommandID, workItem.TransferState, workItem.ResultCode));

                //将指令同步更新至历史记录表 
                workItem.InsertCommandHistory();
            }
        }
        public bool IsReadyForTransferState(enumTransferState transferState)
        {
            return transferState == enumTransferState.CREATE || transferState == enumTransferState.READY || transferState == enumTransferState.NOTREADY;
        }
        public void DoTransferCarrierLocUpdate(string carrierId, string carrierLoc)
        {
            if (carrierId != "" && carrierLoc != "")
            {
                TransferWorkItem jobByCarrier = this.GetJobByCarrierID(carrierId);
                if (jobByCarrier != null)
                {
                    //更新指令的当前位置状态
                    jobByCarrier.CarrierLoc = carrierLoc;
                    //更新指令的状态
                    jobByCarrier.IsOnShuttle = true;
                    jobByCarrier.TransferState = enumTransferState.ONSHUTTLE;
                    LogHelper.loggerInfo(string.Format("更新指令[{0}]状态为:[{1}]", jobByCarrier.CommandID, jobByCarrier.TransferState));
                    this.InnerPublishEvent(jobByCarrier.CommandID, TransferEvent.TransferEventType.UPDATE_TRANSFER);
                }
            }
        }
        public void DoTransferCarrierIdCommandIdUpdate(string carrierId)
        {
            if (carrierId != "")
            {
                TransferWorkItem jobByCarrier = this.GetJobByCarrierID(carrierId);
                if (jobByCarrier != null)
                {
                    Carrier carrier = Naming.GetCarrierManager().GetCarrier(carrierId);
                    //更新指令的当前位置状态
                     carrier.CommandID = jobByCarrier.CommandID;
                    LogHelper.loggerInfo(string.Format("重新绑定物料[{0}]的指令为:[{1}]", carrierId, jobByCarrier.CommandID));
                    this.InnerPublishEvent(jobByCarrier.CommandID, TransferEvent.TransferEventType.UPDATE_TRANSFER);
                }
            }
        }
        public void InnerPublishEvent(string commandID, TransferEvent.TransferEventType type)
        {
            Naming.PublishEvent(TransferEvent.FormSubject(this.hostDevice.ElementId), new TransferEvent(this.hostDevice.ElementId, EquipmentType.ValueToString(this.hostDevice.EquipmentType), commandID, type));
        }

        //By CSTID获取对应的COMMAND
        public TransferWorkItem GetWorkItemByCarrierID(string carrierId)
        {
            TransferWorkItem result;
            foreach (TransferWorkItem current in this.workList)
            {
                if (current.CarrierID.Equals(carrierId))
                {
                    result = current;
                    return result;
                }
            }
            result = null;
            return result;
        }
        /// <summary>
        /// 获取能够作为起始地的单元
        /// </summary>
        /// <returns></returns>
        public List<string> GetCommandSources()
        {
            List<string> commandSources = new List<string>();
            foreach (ConveyorBuffer conveyorBuffer in this.hostDevice.ConveyorBuffers.Values)
            {
                if (ConveyorBuffer.Constants.CVUNLOAD.Equals(conveyorBuffer.Cvtype))
                {
                    string lifterPortID = conveyorBuffer.LifterPortID;
                    LifterPort lifterPort = this.hostDevice.GetLifterPort(lifterPortID);
                    if (lifterPort.IsCombine)
                    {
                        string CVID = conveyorBuffer.HostID;
                        commandSources.Add(CVID);
                    }
                    else
                    {
                        commandSources.Add(lifterPort.HostID);
                    }
                }
            }
            return commandSources;
        }
    }
}
